package com.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class ImageCodeUtil {
	
	public static final int WIDTH = 70;
	public static final int HEIGHT = 25;
	public static final int SIZE = 4;
	public static final int FONT_SIZE = 20;
	
	public static Map<String, BufferedImage> getImage(){
		Map<String, BufferedImage> map = new HashMap<String, BufferedImage>();
		BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
				BufferedImage.TYPE_INT_RGB);
		Graphics g = image.getGraphics();
		Random random = new Random();
		g.setColor(getRandColor(200, 255));
		g.fillRect(0, 0, WIDTH, HEIGHT);
		g.setFont(new Font("Times New Roman", Font.PLAIN, FONT_SIZE));
		g.setColor(getRandColor(160, 200));
		for (int i = 0; i < 155; i++) {
			int x = random.nextInt(WIDTH);
			int y = random.nextInt(HEIGHT);
			int x1 = random.nextInt(12);
			int y1 = random.nextInt(12);
			g.drawLine(x, y, x + x1, y + y1);
		}
		String code = "";
		char[] chars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };	
//		, 'A',
//				'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
//				'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
		int n = chars.length;
		for (int i = 0; i < SIZE; i++) {
			int m = random.nextInt(n);
			String rand = String.valueOf(chars[m]);
			chars[m] = chars[chars.length - i - 1];
			n--;
			code += rand;
			g.setColor(new Color(20 + random.nextInt(110), 20 + random
					.nextInt(110), 20 + random.nextInt(110)));
			g.drawString(rand, 15 * i + 5, 20);
		}
		map.put(code, image);
		return map;
	}
	
	public static Color getRandColor(int fc, int bc) {
		Random random = new Random();
		if (fc > 255)
			fc = 255;
		if (bc > 255)
			bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}
}
